
const { onEmit } = require('../../baseService/broadService/processor/broadcastProcessor');
const { asyncTopicConstants } = require('../../../common/constans/asyncTopicContans')
const EnvContext = require('../../../common/context/EnvContext');
const { envConst } = require('../../../common/constans/envConstans');
const fileUtil = require('../../../common/utils/fileUtil')
const { createView } = require('../../winService/baseWinService/createWebView')
const path = require('path')

exports.doRunListPlugin = function (request) {
    /*
    1. 获取该list插件的preload
    2. 覆盖主渲染进程的view的preload
    3. 读取renderJs并返回
    4. 渲染进程主窗口拿到当前运行插件信息
    5. 渲染进程view获取到renderJs
    6. 执行renderJs的enter并渲染结果
    */
    const preloadPath = getPreloadPath(request)
    const pluginId = request.plugin.cmdInfo.pluginInfo.pluginId
    switchMainPreload(preloadPath, pluginId, () => {
        const renderJs = getRenderJs(request)
        broadcastFeatureCode({ renderJs: renderJs, payload: request })
    })

}

function broadcastFeatureCode(request) {
    const theWin = EnvContext.getInstance().getMainWin()
    onEmit(asyncTopicConstants.onTriggerForListPlugin, request, theWin)
}



function getRenderJs(request) {
    let renderJsPath
    if (envConst.dev()) {
        renderJsPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.development.renderJs
        if (!renderJsPath.startsWith("/")) {
            renderJsPath = path.join(fileUtil.getPluginPathByPluginId(request.plugin.cmdInfo.pluginInfo.pluginId), renderJsPath)
        }
    } else {
        renderJsPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.renderJs
        if (!renderJsPath.startsWith("/")) {
            renderJsPath = path.join(fileUtil.getPluginPathByPluginId(request.plugin.cmdInfo.pluginInfo.pluginId), renderJsPath)
        }
    }

    return fileUtil.openFile(renderJsPath)
}


function getPreloadPath(request) {

    const pluginId = request.plugin.cmdInfo.pluginInfo.pluginId

    let preloadPath = ""
    if (envConst.dev()) {
        preloadPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.development.preload
        if (!preloadPath.startsWith("/")) {
            preloadPath = path.join(fileUtil.getPluginPath(), pluginId, preloadPath)
        }
    } else {
        preloadPath = request.plugin.cmdInfo.pluginInfo.pluginInfo.preload
        if (!preloadPath.startsWith("/")) {
            preloadPath = path.join(fileUtil.getPluginPath(), pluginId, preloadPath)
        }
    }
    return preloadPath
}




function switchMainPreload(preloadPath, pluginId, callback) {
    const mainWindow = EnvContext.getInstance().getMainWin()
    createView(mainWindow, preloadPath, "http://localhost:8000/list", pluginId, null, callback)
}